package com.jsz.peini.controller.app;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.LinkedHashMap;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;


@Controller
public class FileController {
	private static final Logger logger = LoggerFactory.getLogger(FileController.class);
	/**
	 * 测试用
	 */
	@RequestMapping(value="/getPic")
	public String getpic(HttpServletResponse response,int userId) throws IOException {
		response.setContentType("image/jpeg"); // 设置返回内容格式
		String picurl = "";
		if(userId==1){
			picurl = "d:/12.jpg";       //括号里参数为文件图片路径
		}else{
			picurl = "d:/1234.jpg";       //括号里参数为文件图片路径
		}
		File file = new File(picurl);
		if(file.exists()){   //如果文件存在
			InputStream in = new FileInputStream(picurl);   //用该文件创建一个输入流
			OutputStream os = response.getOutputStream();  //创建输出流
			byte[] b = new byte[1024];  
			while( in.read(b)!= -1){ 
			os.write(b);     
			}
			in.close(); 
			os.flush();
			os.close();
		}
		return null;
	}
	
	/**
	 * 测试用
	 */
	@RequestMapping(value="/setPic",method = RequestMethod.POST)
	@ResponseBody
	public Object setPic(HttpServletRequest request,@RequestParam("file") MultipartFile file) throws IOException {
		LinkedHashMap<String, Object> infoMap = new LinkedHashMap<String, Object>();
		// 判断文件是否为空  
			if (!file.isEmpty()) {  
            	try {  
	                // 文件保存路径  
	                String filePath = request.getSession().getServletContext().getRealPath("/") + "upload/report/"  
	                        + file.getOriginalFilename();  
	                File filedir = new File(filePath);
	                if(!filedir.exists()){
	                	filedir.mkdirs();
	                }
	                // 转存文件  
	                file.transferTo(new File(filePath));  
            	} catch (Exception e) {  
            		logger.error(e.getMessage(),e);  
            	}  
			}  
	    return infoMap;
	}
}
